<?php
/**
 * Users Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class UsersController extends AppController {
/**
 * Controller name
 *
 * @var string
 * @access public
 */
    var $name = 'Users';
    
    var  $components = array(
		'Email', 'Cookie' => array('name' => 'easy', 'time' => '+2 weeks'),
	);
    
    
    
/**
 * Models used by the Controller
 *
 * @var array
 * @access public
 */
    var $uses = array('User');

    function beforeFilter() {
        parent::beforeFilter();
       
    }

    function admin_index() {
        $this->pageTitle = __('Users', true);

        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    function admin_add() {
        if (!empty($this->data)) {
            $this->User->create();
            $this->data['User']['activation_key'] = md5(uniqid());
            if ($this->User->save($this->data)) {
                $this->redirect(array('action' => 'index'));
            } else {
                unset($this->data['User']['password']);
            }
        } else {
            $this->data['User']['role_id'] = 2; // default Role: Registered
        }
        $roles = $this->User->Role->find('list');
        $this->set(compact('roles'));
    }

    function admin_edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->redirect(array('action' => 'index'));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
        $roles = $this->User->Role->find('list');
        $this->set(compact('roles'));
    }

    function admin_reset_password($id = null) {
        if (!$id && empty($this->data)) {
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->redirect(array('action' => 'index'));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
    }

    function admin_delete($id = null) {
        if (!$id) {
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->delete($id)) {
            $this->redirect(array('action' => 'index'));
        }
    }

    function admin_login() {
        $this->pageTitle = __('Admin Login', true);
        $this->layout = "admin_login";
    	if ($cookie = $this->Cookie->read('User')) {
			$this->Session->write('Auth.User', $cookie);
		}
		
		if ($id = $this->Auth->user('id')) {
			//if (!empty($this->data['User']['remember_me'])) 
			{
				$this->Cookie->write('User', $this->Session->read('Auth.User'),true,31536000);
			}
			
			//$this->Session->write('Auth.User.Permission', $this->User->groups($id));

			$this->User->id = $id;
			$this->User->save(array(
				'id' => $id,
				'username' => $this->Auth->user('username'),
				'email' => $this->Auth->user('email'),
				'last_login' => date('Y-m-d H:i:s')
			));

			if ($redirect = $this->Session->read('Access.redirect')) {
				$this->Session->delete('Access');
				$this->Session->delete('Auth.redirect');
				$message = "access:$redirect";
			} else {
				$redirect = $this->Auth->redirect();
				$message = "auth:$redirect";
			}
			if (strpos($redirect, 'login') !== false || strpos($redirect, 'users/add') !== false || $redirect == '/') {
				$redirect = '/';
			}
			$this->redirect($redirect);
			//$this->flash($message, $redirect);
			// /return;
		}

		if (!empty($this->data['User'])) {
			//$this->Auth->fields['password'] = 'tmp_pass';
			//$this->data['User']['tmp_pass'] = $this->Auth->data['User']['password'];

			if ($this->Auth->login($this->data)) {
				$this->User->id = $this->Auth->user('id');
				$this->User->save(array(
					'id' => $id,
					'username' => $this->Auth->user('username'),
					'email' => $this->Auth->user('email'),
					'last_login' => date('Y-m-d H:i:s'),
					'tmp_pass' => null,
				));
				$this->redirect('/admin');
			}
		}

		if (!empty($this->data['User']['username'])) {
			$this->redirect(array('action' => 'forgotten'), 401);
		}
    }

    function admin_logout() {
        $this->redirect($this->Auth->logout());
    }

    function index() {
        $this->pageTitle = __('Users', true);
    }

    function register() {
        $this->pageTitle = __('Register', true);
        if (!empty($this->data)) {
            $this->User->create();
            $this->data['User']['role_id'] = 2; // Registered
            $this->data['User']['activation_key'] = md5(uniqid());
            $this->data['User']['status'] = 0;
            if ($this->User->save($this->data)) {
                $this->data['User']['password'] = null;
                $this->Email->from = Configure::read('Site.title') . ' '
                    . '<croogo@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])).'>';
                $this->Email->to = $this->data['User']['email'];
                $this->Email->subject = __('[' . Configure::read('Site.title') . '] Please activate your account', true);
                $this->Email->template = 'register';
                $this->set('user', $this->data);
                $this->Email->send();

                $this->redirect(array('action' => 'login'));
            }
        }
    }

    function activate($username = null, $key = null) {
    	
        if ($username == null || $key == null) {
        	$user = $this->Auth->user();   
        	print_r($user); 		
    		if(!empty($user['User'])&& $user['User']['status']==0)
    		{
    			//'您的用户没有激活';
    			echo '==';
    			//exit;
    		}
    		else
    		{
            	$this->redirect(array('action' => 'login'));
    		}
        }
        else
        {
	        if ($this->User->hasAny(array(
	                'User.username' => $username,
	                'User.activation_key' => $key,
	                'User.status' => 0,
	            ))) {
	            $user = $this->User->findByUsername($username);	                   
	            $this->User->id = $user['User']['id'];
	            $this->User->saveField('status', 1);
	            $activation_key = md5(uniqid());
	            $this->User->saveField('activation_key', $activation_key);
	            
	            // 更新cookie与session
	            $user['User']['status']  = 1;
	            $user['User']['activation_key'] = $activation_key;  
	            $this->Session->write('Auth.User', $user['User']);
	            $this->Cookie->write('User',$user['User']);
	            
	        }
	        //exit;    
	        $this->redirect(array('action' => 'login'));
        }
    }

    function edit() {}

    function forgot() {
        $this->pageTitle = __('Forgot Password', true);

        if (!empty($this->data) && isset($this->data['User']['username'])) {
            $user = $this->User->findByUsername($this->data['User']['username']);
            if (!isset($user['User']['id'])) {
                $this->redirect(array('action' => 'login'));
            }

            $this->User->id = $user['User']['id'];
            $activationKey = md5(uniqid());
            $this->User->saveField('activation_key', $activationKey);
            $this->set(compact('user', 'activationKey'));

            $this->Email->from = Configure::read('Site.title') . ' '
                    . '<croogo@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])).'>';
            $this->Email->to = $user['User']['email'];
            $this->Email->subject = '[' . Configure::read('Site.title') . '] ' . __('Reset Password', true);
            $this->Email->template = 'forgot_password';
            if ($this->Email->send()) {
                $this->redirect(array('action' => 'login'));
            }
        }
    }

    function reset($username = null, $key = null) {
        $this->pageTitle = __('Reset Password', true);

        if ($username == null || $key == null) {
            $this->redirect(array('action' => 'login'));
        }

        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.username' => $username,
                'User.activation_key' => $key,
            ),
        ));
        if (!isset($user['User']['id'])) {
            $this->redirect(array('action' => 'login'));
        }

        if (!empty($this->data) && isset($this->data['User']['password'])) {
            $this->User->id = $user['User']['id'];
            $user['User']['password'] = Security::hash($this->data['User']['password'], null, true);
            $user['User']['activation_key'] = md5(uniqid());
            if ($this->User->save($user['User'])) {
                $this->redirect(array('action' => 'login'));
            }
        }

        $this->set(compact('user', 'username', 'key'));
    }

    function login() {    	
        //$this->pageTitle = __('Log in', true);
        //print_r($this->Session->read('Auth.User'));        
        if ($cookie = $this->Cookie->read('User')) {
			$this->Session->write('Auth.User', $cookie);
		}
		
		if ($id = $this->Auth->user('id')) {
			//if (!empty($this->data['User']['remember_me'])) 
			{
				$this->Cookie->write('User', $this->Session->read('Auth.User'),true,31536000);
			}

			//$this->Session->write('Auth.User.Permission', $this->User->groups($id));

			$this->User->id = $id;
			$this->User->save(array(
				'id' => $id,
				'username' => $this->Auth->user('username'),
				'email' => $this->Auth->user('email'),
				'last_login' => date('Y-m-d H:i:s')
			));

			if ($redirect = $this->Session->read('Access.redirect')) {
				$this->Session->delete('Access');
				$this->Session->delete('Auth.redirect');
				$message = "access:$redirect";
			} else {
				$redirect = $this->Auth->redirect();
				$message = "auth:$redirect";
			}
			if (strpos($redirect, 'login') !== false || strpos($redirect, 'users/add') !== false || $redirect == '/') {
				$redirect = '/';
			}
			$this->redirect($redirect);
			//$this->flash($message, $redirect);
			// /return;
		}

		if (!empty($this->data['User'])) {
			//$this->Auth->fields['password'] = 'tmp_pass';
			//$this->data['User']['tmp_pass'] = $this->Auth->data['User']['password'];

			if ($this->Auth->login($this->data)) {
				$this->User->id = $this->Auth->user('id');
				$this->User->save(array(
					'id' => $id,
					'username' => $this->Auth->user('username'),
					'email' => $this->Auth->user('email'),
					'last_login' => date('Y-m-d H:i:s'),
					'tmp_pass' => null,
				));
				$this->redirect('/');
			}
		}

		if (!empty($this->data['User']['username'])) {
			$this->redirect(array('action' => 'forgotten'), 401);
		}
        
    }

    function logout() {
    	$this->Cookie->destroy('User');
		$this->Auth->logout();
		$this->Session->delete('Access');
		$this->Session->delete('Auth.redirect');
        $this->redirect($this->Auth->logout());
    }

    function view($username) {
        $user = $this->User->findByUsername($username);
        if (!isset($user['User']['id'])) {
            $this->redirect('/');
        }

        $this->pageTitle = $user['User']['name'];
        $this->set(compact('user'));
    }
    
}
?>